package com.lyn.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;

import com.lyn.module_custom_base.adapter.BaseAdapter;
import com.lyn.module_custom_base.dialog.BaseDialog;
import com.lyn.view.R;
import com.lyn.view.databinding.AdapterFileItemBinding;
import com.lyn.view.databinding.DialogFileBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * created by lyn at 2021/11/8
 */
public class FileDialog extends BaseDialog<DialogFileBinding> {

    private String title;
    private String path;
    private String parentDirectory;


    public FileDialog(@NonNull Context context) {
        super(context, R.style.common_dialog);
    }


    public void setPath(String path) {
        this.path = path;
    }

    @Override
    protected DialogFileBinding getViewBinding() {
        return DialogFileBinding.inflate(getLayoutInflater(), null, false);
    }

    @Override
    protected void bindData(DialogFileBinding binding, Dialog dialog) {
        binding.fileListView.setAdapter(adapter);
        new LoadFile(path).execute();
    }

    @Override
    protected void bindListener(DialogFileBinding binding, final Dialog dialog) {

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(parentDirectory)) {
                    dismiss();
                    return;
                }
                new LoadFile(parentDirectory).execute();

            }
        });
        binding.fileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = adapter.getItem(position);
                if (!file.exists()) {
                    return;
                }
                boolean isFile = file.isFile();
                if (isFile) {
                    if (fileDialogCallBack == null) return;
                    fileDialogCallBack.onPath(true, file.getPath(), file);
                } else {
                    new LoadFile(file.getPath()).execute();
                }
            }
        });
        binding.fileListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                File file = adapter.getItem(position);
                if (fileDialogCallBack == null) return true;
                fileDialogCallBack.onPath(false, file.getPath(), file);
                return true;
            }
        });
    }

    @Override
    protected boolean getDispatchKeyEvent() {
        return true;
    }

    @Override
    protected boolean customLengthAndWidth() {
        return true;
    }

    private BaseAdapter<File, AdapterFileItemBinding> adapter = new BaseAdapter<File, AdapterFileItemBinding>() {
        @Override
        protected AdapterFileItemBinding getViewBinding(ViewGroup parent) {
            return AdapterFileItemBinding.inflate(getLayoutInflater(), parent, false);
        }

        @Override
        protected void bindData(AdapterFileItemBinding adapterFileItemBinding, File file, int position) {
            int icon = getFileIcon(file);
            adapterFileItemBinding.icon.setImageResource(icon);
            adapterFileItemBinding.name.setText(file.getName());
            adapterFileItemBinding.path.setText(file.getAbsolutePath());
        }

        @Override
        protected void bindListener(AdapterFileItemBinding adapterFileItemBinding, File file, int position) {

        }
    };


    private class LoadFile extends AsyncTask<Void, String, List<File>> {

        private String path;

        public LoadFile(String path) {
            this.path = path;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected List<File> doInBackground(Void... voids) {
            if (TextUtils.isEmpty(path)) {
                switch (Build.VERSION.SDK_INT) {
                    case Build.VERSION_CODES.LOLLIPOP_MR1:
                        path = "mnt/";
                        break;
                    default:
                        path = "storage";
                        break;
                }
            }
            File file = new File(path);
            if (file == null) return null;
            if (!file.exists()) return null;
            parentDirectory=file.getParent();
            publishProgress(parentDirectory);
            File[] listFiles = file.listFiles();
            if (listFiles == null) return null;
            int length = listFiles.length;
            if (length < 1) return null;
            List<File> fileList = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                File f = listFiles[i];
                if (existFile(f)&&(!f.isFile())) {
                    fileList.add(f);
                }
            }
            for (int i = 0; i < length; i++) {
                File f = listFiles[i];
                if (existFile(f)&&f.isFile()) {
                    fileList.add(f);
                }
            }
            return fileList;
        }


        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            if (values==null)return;
            binding.parentDirectory.setText(values[0]);
        }

        @Override
        protected void onPostExecute(List<File> files) {
            super.onPostExecute(files);
            if (files == null) return;
            adapter.setData(files);
        }
    }

    private boolean existFile(File file) {
        if (file.isFile()){
            return true;
        }
        File[] listFiles = file.listFiles();
        if (listFiles == null) return false;
        if (listFiles.length == 0) return false;
        return true;
    }

    private int getFileIcon(File file) {
        if (!file.isFile()){
            return R.drawable.folder;
        }
        String absolutePath=file.getAbsolutePath();
        if (TextUtils.isEmpty(absolutePath)) {
            return R.drawable.file;
        }
        if (absolutePath.endsWith(".apk")) {
            return R.drawable.apk_file;
        }
        if (absolutePath.endsWith(".txt")) {
            return R.drawable.txt_file;
        }
        if (absolutePath.endsWith(".jpg")) {
            return R.drawable.photo_file;
        }
        if (absolutePath.endsWith(".mp4")) {
            return R.drawable.video_file;
        }
        return R.drawable.file;
    }

    private FileDialogCallBack fileDialogCallBack;

    public void setFileDialogCallBack(FileDialogCallBack fileDialogCallBack) {
        this.fileDialogCallBack = fileDialogCallBack;
    }

    public interface FileDialogCallBack {
        void onPath(boolean isFile, String path, File file);
    }
}
